package com.asdc.autoscanfiles.service;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.asdc.autoscanfiles.constant.DictConstants;
import com.asdc.autoscanfiles.entity.Dict;
import com.asdc.autoscanfiles.entity.ImgFileDto;
import com.asdc.autoscanfiles.entity.ImportLog;
import com.asdc.autoscanfiles.repository.ImgFileRepository;
import com.asdc.autoscanfiles.repository.ImportLogRepository;
import com.asdc.autoscanfiles.utils.DateUtils;
import com.asdc.autoscanfiles.utils.StaticUtils;

/**
 * @Author zhangbingyue
 * @Description //TODO $
 * @Date $ $
 * @Param $
 * @return $
 **/
@Service
@Scope("singleton")
public class ImgImportService {

	private static Logger logger = LoggerFactory.getLogger(ImgImportService.class);
	private static Logger importLogger = LoggerFactory.getLogger("import_log");

	private boolean isImporting = false;

	private final static int BATCH_IMPORT_SIZE = 500;

	@Value("${img.filePath}")
	private String filePath;
	@Value("${img.desPath}")
	private String desPath;
	@Value("${img.import.batchSize}")
	private int batchSize;
	@Autowired
	private ImgFileRepository imgFileRepository;
	@Autowired
	private DictService dictService;
	@Autowired
	private EsResultService esResultService;
	@Autowired
	private ImportLogRepository importLogRepository;
	private Map<String, String> stationNameMap = new HashMap<>();

	private String getStationName(String stationCode) {
		if (stationNameMap.containsKey(stationCode)) {
			return stationNameMap.get(stationCode);
		}
		List<Dict> dicts = this.dictService.queryByCodeAndType(stationCode,
				DictConstants.TYPE_AREA);
		if (!CollectionUtils.isEmpty(dicts)) {
			String name = dicts.get(0).getText();
			stationNameMap.put(stationCode, name);
			return name;
		}
		return null;

	}

	private List<File> getSourceFilePathes() {
		List<File> files = new ArrayList<>();
		if (this.filePath.contains(",")) {
			String[] pathes = this.filePath.split(",");
			if (ArrayUtils.isNotEmpty(pathes)) {
				for (String path : pathes) {
					File tmp = new File(path);
					if (tmp.exists() && tmp.isDirectory()) {
						files.add(tmp);
					}
				}
			}

		}
		return files;
	}

    /**
     * 从文件名解析区站号
     *
     * @return
     */
    private String getStationNumberFromFileName(String fileName, String firstChar) {
        String stationNumber = "";
        if (firstChar.startsWith("F") || firstChar.startsWith("R")) { // 降水、风
            stationNumber = fileName.substring(1, 6);
        } else if (firstChar.startsWith("U")) { // 高空
            stationNumber = fileName.substring(29, 34);
        }else if(firstChar.startsWith("")){ //气表
			stationNumber = fileName.substring(28, 33);
		}
		return stationNumber;
	}

    /**
     * 从路径中解析出
	 * SURF_CLI_FJ_PRE_FTM_ARP_JPG、
	 * UPAR_WEW_AH_MUL_FTM_GB11_JPG、
	 * SURF_CLI_BJ_MUL_FTM_QB1_JPG
     *
     * @param file
     * @return
     */
    private String getMiddlePathFromFilePath(File file) {
        File parent = file.getParentFile();
        while (parent != null) {
            String name = parent.getName();
            if (name.contains("_") && name.contains("JPG") && name.length() > 15) {
                return name;
            }
            parent = parent.getParentFile();
        }
        return null;
    }

    /**
     * 高空小气表类型 GB11、GB12、GB13....
     * @param fileName
     * @return
     */
    private String getMiddleBeginPathFromFilePath(String fileName){
        String stationNumber = fileName.substring(20, 24);
        return stationNumber;
    }

    /**
     * 气表类型 QB1
     * @param fileName
     * @return
     */
    private String getSurfMiddleBeginPathFromFilePath(String fileName){
        String stationNumber = fileName.substring(20, 23);
        return stationNumber;
    }

	/**
	 * 生成目标文件路径规则如下：
	 * 降水：TB3/AFTER_1951/SURF/ZJ/PRE/SURF_CLI_FJ_PRE_FTM_ARP_JPG/DATASETS/区站号/
	 * 风：TB3/AFTER_1951/SURF/ZJ/WIND/SURF_CLI_FJ_WIN_FTM_ARP_JPG/DATASETS/区站号/1998
     * 高空小气表: TB3/AFTER_1951/UPAR/QB/GB11/UPAR_WEW_FJ_MUL_FTM_GB11_JPG/DATASETS/区站号/年份
	 * 气表：TB3/AFTER_1951/SURF/QB/QB1/SURF_CLI_BJ_MUL_FTM_QB1_JPG/DATASETS/区站号/
	 * @param source
	 * @return
	 */
	private String generateDestFilePath(File source) {
		String name = source.getName().toUpperCase();
		String firstChar = name.substring(0, 1);
		switch (firstChar) {
		case "F":
		case "R":
			boolean isWind = firstChar.endsWith("F");
			// 风,降水
			if (name.length() < 20) {
				// 非法文件名
				return null;
			}
			String middlePath = this.getMiddlePathFromFilePath(source);
			String stationNumber = this.getStationNumberFromFileName(name, firstChar);
			if (middlePath == null) {
				// 非法文件名
				return null;
			}
			if (stationNumber == null) {
				// 非法文件名
				return null;
			}
			StringBuilder path = new StringBuilder("TB3/AFTER_1951/").append(StaticUtils.SURF)
					.append("/")
					.append(StaticUtils.ZJ).append("/")
					.append(isWind ? StaticUtils.WIND : StaticUtils.PRE).append("/")
					.append(middlePath).append("/DATASETS/").append(stationNumber).append("/");
			if (isWind) {
				String year = name.substring(6, 10);
				path.append(year).append("/");
			}
			path.append(name);
			return path.toString();
		case "U":
			boolean isUpar = firstChar.startsWith("U");
			// 高空
			if (name.length() < 51) {
				// 非法文件名
				return null;
			}

            String middleBegin = this.getMiddleBeginPathFromFilePath(name); // 高空小气表类型
            String middlePathU = this.getMiddlePathFromFilePath(source);// 最长的文件名字
            String stationNumberU = this.getStationNumberFromFileName(name, firstChar);// 图片的区站号
            if (middlePathU == null) {
                // 非法文件名
                return null;
            }
            if (stationNumberU == null) {
                // 非法文件名
                return null;
            }
            if (middleBegin == null){
                // 非法文件名
                return null;
            }
            StringBuilder pathU = new StringBuilder("TB3/AFTER_1951/").append(StaticUtils.UPAR)
                    .append("/")
                    .append(StaticUtils.QB).append("/")
                    .append(middleBegin).append("/")
                    .append(middlePathU).append("/DATASETS/").append(stationNumberU).append("/");
            if (isUpar) {
                String year = name.substring(35, 39);
                pathU.append(year).append("/");
            }
            pathU.append(name);
            return pathU.toString();
        case "S":
            // 气表
            if (name.length() < 43) {
                // 非法文件名
                return null;
            }
            String surfMiddleBegin =  this.getSurfMiddleBeginPathFromFilePath(name);
            String surfMiddlePath = this.getMiddlePathFromFilePath(source);
            String surfStationNumber = this.getStationNumberFromFileName(name,firstChar);
            StringBuilder surfPath = new StringBuilder("TB3/AFTER_1951/").append(StaticUtils.SURF)
                    .append("/")
                    .append(StaticUtils.QB).append("/")
                    .append(surfMiddleBegin).append("/")
                    .append(surfMiddlePath).append("/DATASETS/").append(surfStationNumber).append("/");
            surfPath.append(name);
            return surfPath.toString();
		}
		return null;
	}
	private ImgFileDto generateDto(File file, File basePath) {
		ImgFileDto dto = new ImgFileDto();
		String destFileName = this.generateDestFilePath(file);
		if (destFileName == null) {
			logger.error("failed in generating " + file + " dto due to illegal file");
			importLogger.info(file.getPath() + " failed");
			return null;
		}
		File destFile = new File(this.desPath, destFileName);
		dto.setPath(file.getAbsolutePath());
		dto.setNewPath(destFileName);
		return dto;
	}
	
	private boolean moveImageToDest(ImgFileDto dto) {
		File file = new File(dto.getPath());
		File destFile = new File(this.desPath, dto.getNewPath());
		try {
			FileUtils.moveFile(file, destFile);
		}catch(Exception e) {
			logger.error("failed in moving " + file + " to " + destFile, e);
			importLogger.info(file.getPath() + " failed");
			return false;
		}
		return true;
	}
	private ImgFileDto copyImageToDest(File file, File basePath) {
		ImgFileDto dto = new ImgFileDto();
		String destFileName = this.generateDestFilePath(file);
		if (destFileName == null) {
			logger.error("failed in copying " + file + " due to illegal file");
			importLogger.info(file.getPath() + " failed");
			return null;
		}
		File destFile = new File(this.desPath, destFileName);
		try {
//			FileUtils.copyFile(file, destFile);
			FileUtils.moveFile(file, destFile);
			dto.setPath(file.getAbsolutePath());
			dto.setNewPath(destFileName);
		} catch (IOException e) {
			logger.error("failed in moving " + file + " to " + destFile, e);
			importLogger.info(file.getPath() + " failed");
			return null;
		}
		return dto;

	}

	private String getProvinceCodeFromFilePath(File file) {
		String middlePath = this.getMiddlePathFromFilePath(file);
		if (middlePath != null) {
			String[] segs = middlePath.split("_");
			if (ArrayUtils.isNotEmpty(segs)) {
				String provinceCode = segs[2].trim();
				return provinceCode;
			}
		}
		return null;
	}

	private void fillDtoProperties(ImgFileDto dto, File image) throws ParseException {
		String upperName = image.getName().toUpperCase();
		String stationNumber = this.getStationNumberFromFileName(image.getName(), upperName);
		dto.setAreaNumber(stationNumber);
		dto.setProvinceCode(this.getProvinceCodeFromFilePath(image));
		String provinceName = this.dictService.getProvinceMap().get(dto.getProvinceCode());
		dto.setProvinceName(provinceName);
		dto.setSheng(dto.getProvinceName());
		dto.setAreaName(this.getStationName(dto.getAreaNumber()));
		dto.setFileName(image.getName());
		String fullPath = image.getAbsolutePath();
		if (fullPath.contains(StaticUtils.SURF)) {
			dto.setLevel1(StaticUtils.SURF);
		} else if (fullPath.contains(StaticUtils.RADI)) {
			dto.setLevel1(StaticUtils.RADI);
		} else if (fullPath.contains(StaticUtils.AGME)) {
			dto.setLevel1(StaticUtils.AGME);
		} else if (fullPath.contains(StaticUtils.UPAR)) {
			dto.setLevel1(StaticUtils.UPAR);
		}
		String fileName = image.getName();
		if (upperName.startsWith("F")) {
			// 风
			dto.setLevel2(StaticUtils.ZJ);
			dto.setLevel3(StaticUtils.WIND);
			dto.setElementType("F");
		} else if (upperName.startsWith("R")) {
			// 降水
			dto.setLevel2(StaticUtils.ZJ);
			dto.setLevel3(StaticUtils.PRE);
			dto.setElementType("R");

        } else if (upperName.startsWith("UPAR")) {
            // 高空
            dto.setLevel2(StaticUtils.QB);
            dto.setLevel3(this.getMiddleBeginPathFromFilePath(fileName));
            dto.setElementType("UPAR");

        }else if(upperName.startsWith("SURF")){
			// 气表
			dto.setLevel2(StaticUtils.WR);
			dto.setLevel3(this.getSurfMiddleBeginPathFromFilePath(fileName)); //QB1
			dto.setElementType("UPAR");
		}
        if (upperName.startsWith("R") || upperName.startsWith("F")) {
			int beginDate = Integer.parseInt(upperName.substring(12, 14));
            dto.setBeginDateStr(upperName.substring(6, 14));// 开始日期
            if (image.getName().length() == 20) {
				int endDate = Integer.parseInt(upperName.substring(14, 16));
				if (endDate < beginDate) {
					dto.setEndDateStr(DateUtils.getYearMonthNoSpaceStr(
							DateUtils.getNextMonthFirstDay(dto.getBeginDate()))
							+ fileName.substring(14, 16));

				} else {
					dto.setEndDateStr(fileName.substring(6, 12) + fileName.substring(14, 16));
				}
                dto.setTypeValue("");
            } else if (fileName.length() == 21) {
				int endDate = Integer.parseInt(upperName.substring(14, 16));
				if (endDate < beginDate) {
					dto.setEndDateStr(DateUtils.getYearMonthNoSpaceStr(
							DateUtils.getNextMonthFirstDay(dto.getBeginDate()))
							+ fileName.substring(14, 16));
				} else {
					dto.setEndDateStr(fileName.substring(6, 12) + fileName.substring(14, 16));
				}
                dto.setEndDateStr(fileName.substring(6, 12) + fileName.substring(14, 16));
                dto.setType(fileName.substring(16, 17));
                dto.setTypeValue("");
            } else if (fileName.length() == 22) {
                dto.setEndDateStr(fileName.substring(6, 10) + fileName.substring(14, 18));
                dto.setTypeValue("无降水文件");
            } else if (fileName.length() == 23) {
                dto.setEndDateStr(fileName.substring(6, 10) + fileName.substring(14, 18));
                dto.setType(fileName.substring(18, 19));
                dto.setTypeValue("缺测文件");
            } else if (fileName.length() == 24) {
                dto.setEndDateStr(fileName.substring(6, 10) + fileName.substring(14, 18));
                dto.setType(fileName.substring(18, 20));
                dto.setTypeValue("");
            }
        } else if (upperName.startsWith("UPAR")) {
            dto.setBeginDateStr(upperName.substring(35, 43));
            dto.setEndDateStr(upperName.substring(35, 43));
            dto.setType("");
            dto.setTypeValue("");
        }else if(upperName.startsWith("SURF")){
			// 获取该月第一天和最后一天
			Map<String, String> dateMap = DateUtils.getFirstDayAndLastDayOfMonth(upperName.substring(34, 40), "yyyyMM", "yyyyMMdd");
			dto.setBeginDateStr(dateMap.get("firstDay"));
			dto.setEndDateStr(dateMap.get("lastDay"));
			dto.setType("");
			dto.setTypeValue("");
		}

	}

	private int getBatchSize() {
		return this.batchSize;
	}

	private void saveImagesAndCleanList(List<File> images, File basePath) {
		List<ImgFileDto> dtos = new ArrayList<>();
		long l1 = System.currentTimeMillis();
		for (File file : images) {
			try {
				ImgFileDto dto = this.generateDto(file, basePath);
//				this.copyImageToDest(file, basePath);
				if (dto != null) {
					this.fillDtoProperties(dto, file);
					if (dto.getEndDate() == null) {
						dto.setEndDateStr("29990101");
					}
					if (dto.getBeginDate() == null) {
						dto.setBeginDateStr("19000101");
					}
					boolean isMoved = this.moveImageToDest(dto);
					if(isMoved) {
						dtos.add(dto);
					}
					
				}
			} catch (Exception e) {
				logger.error("error in adding image:" + file, e);
			}

		}
		long l2 = System.currentTimeMillis();
		if (logger.isInfoEnabled()) {
			logger.info("copying " + dtos.size() + "files uses " + (l2 - l1));
		}
		try {
			int[] rets = this.imgFileRepository.batchAddImgFileProject(dtos);
			long l3 = System.currentTimeMillis();
			if (logger.isInfoEnabled()) {
				logger.info("adding " + dtos.size() + "files to db uses" + (l3 - l2));
			}
			if (rets != null && rets.length > 0) {

				this.esResultService.saveToEs();
				long l4 = System.currentTimeMillis();
				if (logger.isInfoEnabled()) {
					logger.info("adding " + dtos.size() + "files to es uses" + (l4 - l3));
				}
				this.cleanOldFilesAndAddLogs(dtos);
				long l5 = System.currentTimeMillis();
				if (logger.isInfoEnabled()) {
					logger.info(
							"cleaning " + dtos.size() + "files and adding logs uses" + (l5 - l4));
				}
			}

		} catch (Exception e) {
			logger.error("failed in saving to db", e);
		}
		images.clear();

	}

	private void addImageFile(List<File> images, File image, File basePath) {
		images.add(image);
		if (images.size() >= this.getBatchSize()) {
			this.saveImagesAndCleanList(images, basePath);
		}
	}

	private ImportLog generateImportLog(ImgFileDto dto) {
		ImportLog log = new ImportLog();
		log.setUpdateTime(new Date());
		log.setFileName(dto.getFileName());
		log.setFilePath(dto.getPath());
		return log;
	}

	private void deleteOldFile(String filePath) {
		File file = new File(filePath);
		if (file.exists() && file.isFile()) {
			file.delete();
		}
	}

	private void cleanOldFilesAndAddLogs(List<ImgFileDto> dtos) {
		List<ImportLog> logs = new ArrayList<>();
		for (ImgFileDto dto : dtos) {
			logs.add(this.generateImportLog(dto));
			this.deleteOldFile(dto.getPath());
		}
		this.importLogRepository.batchAdd(logs);

	}

	private void recurseDirForJPG(File path, List<File> images, File basePath) {
		if (images == null) {
			images = new ArrayList<>();
		}
		if (path.isDirectory()) {
			File[] files = path.listFiles();
			if (ArrayUtils.isNotEmpty(files)) {
				for (File file : files) {
					if (file.isDirectory()) {
						this.recurseDirForJPG(file, images, basePath);
					} else {
						String name = file.getName().toLowerCase();
						if (name.endsWith("jpg") || name.endsWith("jpeg")) {
							// 现在只处理风和降水以及气表
							if (name.startsWith("f") || name.startsWith("r") 
									|| name.startsWith("upar") || name.startsWith("surf")
									) {
								this.addImageFile(images, file, basePath);
							}

						}
					}
				}
			}
			if (!CollectionUtils.isEmpty(images)) {
				this.saveImagesAndCleanList(images, basePath);
			}
		}
	}

	public void importFileAsync() {
		new Thread() {

			@Override
			public void run() {
				ImgImportService.this.importFile();
			}

		}.start();
	}

	/**
	 * 图片传输
	 */
	public void importFile() {
		if (this.isImporting) {
			logger.warn("importing is ongoing");
			return;
		}
		this.isImporting = true;
		try {
			List<File> baseFilePathes = this.getSourceFilePathes();
			if (logger.isInfoEnabled()) {
				logger.info("importing begin");
				logger.info("import dirs:" + ArrayUtils.toString(baseFilePathes));
			}
			if (!CollectionUtils.isEmpty(baseFilePathes)) {
				for (File basePath : baseFilePathes) {
					this.recurseDirForJPG(basePath, null, basePath);
				}
			}
		} catch (Exception e) {
			logger.error("importing error.", e);
		} finally {
			this.isImporting = false;
		}

		// File dir = new File(filePath);
		// File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
		// if (files != null) {
		// for (int i = 0; i < files.length; i++) {
		// if (files[i].isDirectory()) {
		// if (files[i].getName().equals(StaticUtils.SURF)) { // 一级分类：地面
		// File[] files1 = files[i].listFiles(); // 二级+三级分类:
		// // 自记+（风、降水）
		// for (File file : files1) {
		// if (file.isDirectory()) {
		// // 获取文件目录
		// String filePath = "";
		// String[] path = file.getName().split("-");
		// if (path.length > 1) {
		// filePath = path[0] + "/" + path[1];
		// } else if (path.length == 1) {
		// filePath = path[0];
		// }
		//
		// List<File> filelist = new ArrayList<>();
		// filelist = this.getFileList(filelist, file.getPath());
		// if (filelist.size() > 0) {
		// // 移动文件到目标目录
		// this.onMoveFile(filelist,
		// desPath + StaticUtils.SURF + "/" + filePath);
		// /* 保存文件到实体类 */
		// List<ImgFileDto> imgFiles = saveFileSURF(filelist,
		// StaticUtils.SURF, file.getName(), filePath);
		// /* 导入数据导数据库 */
		// long begin = System.currentTimeMillis();
		// logger.info("---开始导入数据---类型：" + StaticUtils.SURF);
		// batchAddImgFileProject(imgFiles);// 批量保存数据库
		// logger.info("----导入结束-----用时："
		// + (System.currentTimeMillis() - begin));
		// }
		// }
		// }
		//
		// }
		//
		// }
		// }
		// }
	}


	// 地面--- 解析保存所有文件
//	public List<ImgFileDto> saveFileSURF(List<File> filelist, String filePath1, String filePath2,
//			String filePath) {
//		// 查询区站与省份的对应关系
//		Map<String, String> shengMap = dictService.getList("0", "1");
//
//		List<ImgFileDto> imgFiles = new ArrayList<>();
//		for (File file : filelist) {
//			String fileName = file.getName();
//			ImgFileDto imgFile = new ImgFileDto();
//			imgFile.setLevel1(filePath1);
//			imgFile.setLevel2(filePath2.split("-").length > 0 ? filePath2.split("-")[0] : "");
//			imgFile.setLevel3(filePath2.split("-").length > 1 ? filePath2.split("-")[1] : "");
//			imgFile.setPath(file.getPath());// 相对路径
//			imgFile.setNewPath("/" + filePath1 + "/" + filePath + "/" + file.getName());
//			imgFile.setElementType(fileName.substring(0, 1)); // 要素代码
//			imgFile.setAreaNumber(fileName.substring(1, 6));// 区站号
//			imgFile.setSheng(shengMap.get(fileName.substring(1, 6)));
//			imgFile.setBeginDateStr(fileName.substring(6, 14));// 开始日期
//			imgFile.setFileName(fileName);
//			if (fileName.length() == 20) {
//				imgFile.setEndDateStr(fileName.substring(6, 12) + fileName.substring(14, 16));
//				imgFile.setTypeValue("");
//				imgFiles.add(imgFile);
//			} else if (fileName.length() == 21) {
//				imgFile.setEndDateStr(fileName.substring(6, 12) + fileName.substring(14, 16));
//				imgFile.setType(fileName.substring(16, 17));
//				imgFile.setTypeValue("");
//				imgFiles.add(imgFile);
//			} else if (fileName.length() == 22) {
//				imgFile.setEndDateStr(fileName.substring(6, 10) + fileName.substring(14, 18));
//				imgFile.setTypeValue("无降水文件");
//				imgFiles.add(imgFile);
//			} else if (fileName.length() == 23) {
//				imgFile.setEndDateStr(fileName.substring(6, 10) + fileName.substring(14, 18));
//				imgFile.setType(fileName.substring(18, 19));
//				imgFile.setTypeValue("缺测文件");
//				imgFiles.add(imgFile);
//			} else if (fileName.length() == 24) {
//				imgFile.setEndDateStr(fileName.substring(6, 10) + fileName.substring(14, 18));
//				imgFile.setType(fileName.substring(18, 20));
//				imgFile.setTypeValue("");
//				imgFiles.add(imgFile);
//			} else {
//				logger.error("文件名称不符合规则--" + fileName);
//				logger.error("相对路径--" + file.getPath());
//			}
//
//		}
//		return imgFiles;
//	}
//
//	// 读取目录下文件列表
//	public List<File> getFileList(List<File> filelist, String strPath) {
//		File dir = new File(strPath);
//		File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
//		if (files != null) {
//			for (int i = 0; i < files.length; i++) {
//				if (files[i].isDirectory()) { // 判断是文件还是文件夹
//					getFileList(filelist, files[i].getPath());
//				} else if (files[i].getName().endsWith("JPG")
//						|| files[i].getName().endsWith("jpg")) { // 只获取jpg结尾的文件
//					filelist.add(files[i]);
//				}
//			}
//		}
//		return filelist;
//	}
//
//	/**
//	 * 移动文件到目标路径
//	 *
//	 * @param filelist
//	 *            文件list
//	 * @param filePath
//	 *            目录
//	 */
//	public void onMoveFile(List<File> filelist, String filePath) {
//		File f1 = new File(filePath);
//		// 如果目的路径不存在，就创建一个
//		if (!f1.exists()) {
//			f1.mkdirs();
//		}
//		// 移动文件
//		long startTime = System.currentTimeMillis();
//		for (File file : filelist) {
//			File file1 = new File(filePath + "\\" + file.getName());
//			fileChannel(file, file1);
//		}
//		long end = System.currentTimeMillis();
//		System.out.println("nioCopy耗费时间:" + (end - startTime));
//	}
//
//	/**
//	 * 使用文件通道，高效复制文件
//	 *
//	 * @param s
//	 * @param t
//	 */
//	private void fileChannel(File s, File t) {
//		FileInputStream fi = null;
//		FileOutputStream fo = null;
//		FileChannel in = null;
//		FileChannel out = null;
//		try {
//			fi = new FileInputStream(s);
//			fo = new FileOutputStream(t);
//			in = fi.getChannel();// 得到对应的文件通道
//			out = fo.getChannel();// 得到对应的文件通道
//			in.transferTo(0L, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
//			// out.transferFrom(in, 0L, (int) in.size());
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			try {
//				fi.close();
//				in.close();
//				fo.close();
//				out.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//
//	}

	public List<ImportLog> getRecentLogs(int size) {
		return this.importLogRepository.getLatestLogs(size);
	}

	public int getLogCount() {
		return this.importLogRepository.getLogCount();
	}

}
